package org.ycx.doc.web.controller;

import com.baidu.unbiz.fluentvalidator.*;
import org.ycx.common.validator.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.ycx.common.constants.RespCode;
import org.ycx.common.dto.RespMSG;
import org.ycx.doc.dao.enums.GroupUsersRole;
import org.ycx.doc.dao.model.*;
import org.ycx.doc.service.IDocProjectService;
import org.ycx.doc.service.IDocProjectVersionService;
import org.ycx.upms.common.constants.SecurityConstants;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * DocProjectcontroller
 * Created by yang on 2017-08-30 17:53:15.
 */
@Controller
@RequestMapping("/project")
public class DocProjectController {

    private static Logger _log = LoggerFactory.getLogger (DocProjectController.class);

    private static final String PRE = "project/";

    @Autowired
    private IDocProjectService service;

    @Autowired
    private IDocProjectVersionService versionService;

    /**
     * 首页
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/index.html")
    public String indexPage(ModelMap modelMap) {
        return PRE + "index";
    }

    /**
     * 新增页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/create.html")
    public String createPage(ModelMap modelMap, Integer gid, HttpSession session) {
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        if (gid == null) {
            List<DocGroup> groups = this.service.findUserGroups (uid);
            modelMap.put ("groups", groups);
        } else {
            modelMap.put ("gid", gid);
        }
        return PRE + "create";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/update/{id}.html")
    public String updatePage(@PathVariable("id") int id, ModelMap modelMap) {
        DocProject bean = this.service.selectByPrimaryKey (id);
        modelMap.put ("bean", bean);
        return PRE + "update";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/{id}.html")
    public String detailPage(@PathVariable("id") int id, ModelMap modelMap, HttpSession session) {
        DocProject bean = this.service.selectByPrimaryKey (id);
        modelMap.put ("bean", bean);
        DocProjectVersionExample dve = new DocProjectVersionExample ();
        dve.createCriteria ().andAppIdEqualTo (id);
        List<DocProjectVersion> versions = this.versionService.selectByExample (dve);
        modelMap.put ("versions", versions);
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        int role = this.service.findRoleByProjectAndUid (bean.getAppId (), uid);
        if (role == GroupUsersRole.Guest.getType ()) {
            return PRE + "projectShow";
        } else {
            return PRE + "projectModule";
        }

    }

    @RequestMapping("/publish/{id}.html")
    public String publishPage(@PathVariable("id") int id, ModelMap modelMap) {
        DocProject bean = this.service.selectByPrimaryKey (id);
        modelMap.put ("bean", bean);
        return PRE + "publish";
    }

    /**
     * 新增功能
     *
     * @param bean
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RespMSG create(DocProject bean, Integer gid, HttpSession session) {
        RespMSG resp = new RespMSG ();
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        ComplexResult result = FluentValidator.checkAll ()
                .on (bean.getAppName (), new NotNullValidator ("项目名称"))
                .on (bean.getAppDesc (), new NotNullValidator ("项目描述"))
                .doValidate ()
                .result (ResultCollectors.toComplex ());
        if (!result.isSuccess ()) {
            resp.initResp (RespCode.FAIL);
            resp.setDesc (ValidationErrorToString.errorToString (result.getErrors (), "\n\r"));
        } else {
            resp.initResp (RespCode.SUCCESS);
            bean.setCreateTs (new Date ());
            bean.setUpdateTs (new Date ());
            bean.setCreateUid (uid);
            bean.setUpdateUid (uid);
            bean.setAppProdVersion (0);
            int count = this.service.addProject (bean, gid);
            resp.setData (bean);
        }
        return resp;
    }

    /**
     * 更新功能
     *
     * @param id
     * @param bean
     * @return
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG update(@PathVariable("id") int id, DocProject bean, HttpSession session) {
        RespMSG resp = new RespMSG ();
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        //TODO 验证数据，验证完成，设定主键为id
        ComplexResult result = FluentValidator.checkAll ()
                .on (bean.getAppName (), new NotNullValidator ("项目名称"))
                .on (bean.getAppDesc (), new NotNullValidator ("项目描述"))
                .doValidate ()
                .result (ResultCollectors.toComplex ());
        if (!result.isSuccess ()) {
            resp.initResp (RespCode.FAIL);
            resp.setDesc (ValidationErrorToString.errorToString (result.getErrors (), "\n\r"));
        } else {
            bean.setUpdateTs (new Date ());
            bean.setUpdateUid (uid);
            int count = service.updateByPrimaryKeySelective (bean);
            resp.initResp (RespCode.SUCCESS);
            resp.setData (bean);
        }
        return resp;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/{appId}/publish", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG delete(@PathVariable("appId") Integer appId, String ids) {
        RespMSG respMSG = new RespMSG ();
        int res = service.publish (appId, ids);
        if (res > 0) {
            respMSG.initResp (RespCode.SUCCESS);
            respMSG.setData (res);
        } else {
            respMSG.initResp (RespCode.FAIL);
        }
        return respMSG;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG delete(@PathVariable("id") Integer ids) {
        int count = service.deleteByPrimaryKey (ids);
        return new RespMSG (RespCode.SUCCESS);
    }


    @RequestMapping("/list")
    @ResponseBody
    public RespMSG list(HttpSession session) {
        RespMSG resp = new RespMSG ();
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        Map<String, Object> data = new HashMap<String, Object> ();
        List<GroupUsersRole> mineRole = new ArrayList<GroupUsersRole> ();
        mineRole.add (GroupUsersRole.Master);
        List<DocProject> mineProjects = this.service.findProjectByUser (uid, mineRole);
        data.put ("mineProjects", mineProjects);

        List<GroupUsersRole> joinRole = new ArrayList<GroupUsersRole> ();
        joinRole.add (GroupUsersRole.Developer);
        joinRole.add (GroupUsersRole.Guest);
        List<DocProject> joinProject = this.service.findProjectByUser (uid, joinRole);

        data.put ("joinProjects", joinProject);

        resp.initResp (RespCode.SUCCESS);
        resp.setData (data);
        return resp;
    }
}
